package utils;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import messagetype.*;

import java.io.*;
import java.net.Socket;

/**
 * @author
 */
@Data
public class Connect {
    private static Connect connect;
    private static final String IP = "192.168.43.233";
    private static final int PORT = 9949;
    private Socket socket = null;
    DataInputStream  dis = null;
    DataOutputStream dos = null;
    BufferedInputStream bis=null;
    BufferedOutputStream bos=null;

    private Connect() throws IOException {
    }


    static {
        try {
            connect = new Connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connect getConnect() {
        return connect;
    }

    public  String  register(User user) throws IOException {
        byte type2 = 0x01;
        String str = JSON.toJSONString(user);
        int len1 = 5 + str.getBytes().length;
        RegMsg rm = new RegMsg(len1, type2, str);
        byte[] data = MsgTool.packMsg(rm);
        dos.write(data);
        dos.flush();

        MsHead msg = MsgTool.readMsgHead(dis);
        byte type1 = msg.getType();
        User user1 = null;
        if (type1 == ByteType.REGISTER_RES_MESSAGE) {
            RegResMsg lrm = (RegResMsg) msg;
            user1 = JSON.parseObject(lrm.getJsonStr(), User.class);
            Byte state = lrm.getState();
            if (state == 0) {
                System.out.println("注册成功");
            }
        }

        byte type4 = ByteType.SAVE_IMAGE_MESSAGE;
        String jsonStr = JSON.toJSONString(user1);
        messagetype.FileMsg fM = new messagetype.FileMsg(5+jsonStr.getBytes().length,type4,jsonStr);
        byte[] bytes = MsgTool.packMsg(fM);
        dos.write(bytes);
        dos.flush();


        File file=new File("photo/temp.png");
        FileInputStream fis = new FileInputStream(file);
        //获取输出流
        bos=new BufferedOutputStream(socket.getOutputStream());
        byte[] buf = new byte[1024];
        int len = 0;
        int count=0;
        while ((len = fis.read(buf)) != -1)
        {
            count+=len;
            bos.write(buf,0,len);
        }
        bos.flush();
        socket.shutdownOutput();
        fis.close();
        bos.close();
        dos.close();
        file.delete();
        return user1.getAccount();

    }

    public boolean startConnect() {
        try {
            socket = new Socket(IP, PORT);
            this.dos = new DataOutputStream(socket.getOutputStream());
            this.dis = new DataInputStream(socket.getInputStream());
            System.out.println("连接成功");
            return true;
        } catch (IOException e) {
            System.out.println("连接失败");
            return false;
        }
    }

    public void sendMessageToFriend(User srcUser, User desUser, String message) throws IOException {
        UserMsgToUser um = new UserMsgToUser(srcUser,desUser,message);
        String privateMsg = JSON.toJSONString(um);
        byte type = 0x03;
        ChatMsg cm = new ChatMsg(privateMsg.getBytes().length+5,type,privateMsg);
        byte[] bytes = MsgTool.packMsg(cm);
        dos.write(bytes);
        dos.flush();

    }

    public void sendMessageToGroup (User srcUser,Group desGroup,String message) throws IOException{
        byte type = 0x17;
        String groupAccount = desGroup.getGroupAccount();
        UserMsgToGroup um = new UserMsgToGroup(message,groupAccount,srcUser);
        String information = JSON.toJSONString(um);
        TogetherChatMsg tt = new TogetherChatMsg(5+information.getBytes().length,type,information);
        byte[] bytes = MsgTool.packMsg(tt);
        dos.write(bytes);
        dos.flush();
    }

    public  User login(String account, String password) throws IOException {
        byte type = 0x02;
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        String string = JSON.toJSONString(user);
        int len = 5+string.getBytes().length;
        LoginMsg rm = new LoginMsg(len, type, string);
        byte[] data = MsgTool.packMsg(rm);
        dos.write(data);
        dos.flush();

        MsHead msg = MsgTool.readMsgHead(dis);
        byte type1 = msg.getType();
        if (type1 == ByteType.LOGIN_RES_MESSAGE) {
            LoginResMsg rrm = (LoginResMsg) msg;
            Byte state = rrm.getState();
            String userStr = rrm.getJsonStr();
            System.out.println(userStr);
            if (state == 0) {
                return JSON.parseObject(userStr, User.class);
            }
        }
        return null;
    }

    public  void getUserByAccount(String account,int flag) throws IOException {
            //flag=0 or 1;

            byte type = 0x07;
            FindMsg fm = new FindMsg(flag,9+account.getBytes().length, type,account);
            byte[] bytes = MsgTool.packMsg(fm);

            dos.write(bytes);
            dos.flush();

    }

    public   void getNewFriends(String account) throws IOException {

        byte type = 0x10;
        FindResList frl = new FindResList(account.getBytes().length+5,type,account);
        byte[] bytes = MsgTool.packMsg(frl);
        dos.write(bytes);
        dos.flush();



//        for (User user : list) {
//            getHeadByAccount(user.getAccount());
//        }


    }

    public  boolean getHeadByAccount(String account) throws IOException {
        File file=new File(String.format("photo/%s.png",account));

        if(file.exists()){
            return false  ;
        }
        byte type = ByteType.FIND_IMAGE_MESSAGE;
        AccountAndImage aai = new AccountAndImage(account,null);
        String accountAndImage = JSON.toJSONString(aai);
        FindImageMsg fim = new FindImageMsg(5+accountAndImage.getBytes().length,type,accountAndImage);
        byte[] bytes = MsgTool.packMsg(fim);
        dos.write(bytes);
        dos.flush();

return true;
    }

    public  void addFriend(User me,User friend) throws IOException {
        UserToUser userToUser=new UserToUser(me,friend);
        byte type = 0x09;
        String json = JSON.toJSONString(userToUser);
        AddFriendMsg afm = new AddFriendMsg(5+json.getBytes().length,type,json);
        byte[] bytes = MsgTool.packMsg(afm);
        dos.write(bytes);
        dos.flush();
    }

    public  void handFriendRequests(User me, User friend, byte state) throws IOException {
        UserToUser userToUser = new UserToUser(me,friend);
        String json = JSON.toJSONString(userToUser);
        byte type = 0x11;
        AddFriendResMsg afrm = new AddFriendResMsg(6+json.getBytes().length,type,state,json);
        byte[] bytes = MsgTool.packMsg(afrm);
        dos.write(bytes);
        dos.flush();
        System.out.println("已同意");
    }

    public void getFriendMessageList(User user) throws IOException {
        byte type = 0x12;
        String jsonUser = JSON.toJSONString(user);
        FriendMsgList fml = new FriendMsgList(5+jsonUser.getBytes().length,type,jsonUser);
         byte[] bytes = MsgTool.packMsg(fml);
         dos.write(bytes);
         dos.flush();
    }

    public void getGroupMessageList(User user) throws IOException {
        byte type = ByteType.GROUP_MESSAGE_LIST;
        String jsonGroupMsg = JSON.toJSONString(user);
        GroupMsgList gm = new GroupMsgList(5+jsonGroupMsg.getBytes().length,type,jsonGroupMsg);
        byte[] bytes = MsgTool.packMsg(gm);
        dos.write(bytes);
        dos.flush();
    }

    public void delete(User srcUser,User desUser) throws IOException {
        byte type = ByteType.DELETE_FRIEND_MESSAGE;
        UserToUser utu=new UserToUser(srcUser,desUser);
        String jsonUser =  JSON.toJSONString(utu);
        DeleteFriendMsg dfm = new DeleteFriendMsg(5+jsonUser.getBytes().length,type,jsonUser);
        byte[] bytes = MsgTool.packMsg(dfm);
        dos.write(bytes);
        dos.flush();
    }

    public void exitGroup(User user, Group group) throws IOException {
        System.out.println(group);
        byte type = ByteType.EXIT_GROUP_MESSAGE;
        ExitGroup eg = new ExitGroup(group,user);
        String json = JSON.toJSONString(eg);
        ExitGroupMsg egm = new ExitGroupMsg(5+json.getBytes().length,type,json);
        byte[] bytes = MsgTool.packMsg(egm);
        dos.write(bytes);
        dos.flush();
    }

    public void createGroup(User user, Group group) throws IOException {
        byte type = ByteType.BUILD_GROUP_MESSAGE;
        String str = null;
        try {
            str = ImgUtil.encodeImage("photo/temp/temp.png");
        } catch (IOException e) {
            e.printStackTrace();
        }
        group.setImage(str);
        String jsonGroup = JSON.toJSONString(group);
        CreateGroupMsg cg = new CreateGroupMsg(5+jsonGroup.getBytes().length,type,jsonGroup);
        byte[] bytes = MsgTool.packMsg(cg);
        dos.write(bytes);
        dos.flush();
    }



    public void disconnect() throws IOException {
        if(bos!=null){
            bos.close();
        }
        if(bis!=null){
            bis.close();
        }
        if(dis!=null){
            dis.close();
        }
        if(dos!=null){
            dos.close();
        }
        socket.close();
    }


    public void userAccessToGroup(User desUser, Group group) throws IOException {
        byte type = ByteType.ADD_USER_TO_GROUP_MESSAGE;

        UserGroupToUser ug = new UserGroupToUser(desUser,group);
        String json = JSON.toJSONString(ug);
        AddUserToGroupMsg aut = new AddUserToGroupMsg(5+json.getBytes().length,type,json);
        byte[] bytes = MsgTool.packMsg(aut);
        dos.write(bytes);
        dos.flush();
    }
}